package com.yetianhua.xml;

import com.yetianhua.pojo.Configuration;
import com.yetianhua.test.Resource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author yetianhua
 * @className XmlConfigBuilder
 * @description TODO
 * @date 2021/6/1
 * @time 21:50
 */
public class XmlConfigBuilder {

    public static Configuration build(InputStream in) throws Exception{
        // 1. 读取配置文件
        Document document = new SAXReader().read(in);
        // 2. 读取datasource的properties
        List<Element> list = document.getRootElement().selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(name, value);
        }

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(properties.getProperty("driverClass"));
        config.setJdbcUrl(properties.getProperty("jdbcUrl"));
        config.setUsername(properties.getProperty("username"));
        config.setPassword(properties.getProperty("password"));
        HikariDataSource dataSource = new HikariDataSource(config);
        /*ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));*/

        Configuration configuration = new Configuration();
        configuration.setDataSource(dataSource);

        List<Element> mapperList = document.selectNodes("//mapper");
        for (Element mapper : mapperList) {
            String resource = mapper.attributeValue("resource");
            new XmlMapperBuiler(configuration).build(Resource.getResourceAsSteam(resource));
        }
        return configuration;

    }

}
